package com.kang.product.tx.service.impl;

import com.kang.product.tx.api.UserService;
import com.kang.product.tx.mapper.UserMapper;
import com.kang.product.tx.model.User;
import com.kang.product.tx.model.UserLoginLogger;
import com.kang.product.tx.mq.MyDiyMQTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private  MyDiyMQTemplate myDiyMQTemplate;

    @Override
    public Map<String, Object> login(String userName, String password) {

        Map<String, Object> result = new HashMap<>();
        if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            result.put("code", 1);
            result.put("msg", "用户名与密码不能为空");
            return result;
        }
        try {
            User queryModel = new User();
            queryModel.setUsername(userName);
            User user = userMapper.selectOne(queryModel);

            if(user == null || !password.equals(user.getPassword()) ) {
                result.put("code", 1);
                result.put("msg", "用户名或密码不正确");
                return result;
            }
            //登录成功，记录登录日志
            UserLoginLogger userLoginLogger = new UserLoginLogger(user.getId(), new Date(System.currentTimeMillis()));
            userLoginLogger.setSerialNumber( UUID.randomUUID().toString().replace("-",""));

            //需要送积分
            if(enbaleActivity()) { //判断是否开启送积分活动，通常可以配置在apollo等配置中心中
                Message<UserLoginLogger> build = MessageBuilder.withPayload(userLoginLogger).build();
                /*MessageHeaders headers = build.getHeaders();
                headers.put("serialNumber", userLoginLogger.getSerialNumber());*/
                //发送事务消息
                myDiyMQTemplate.sendMessageInTransaction("topic_tx:tag",build, "");
            }
            result.put("code", 0);
            result.put("data", user);
        } catch (Throwable e) {
            e.printStackTrace();
            result.put("code", 1);
            result.put("msg" , e.getMessage());
        }
        return result;
    }

    private boolean enbaleActivity() {
        return true;
    }
}
